package wenjie.chen.transfer.controller;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.bytesoft.compensable.Compensable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import wenjie.chen.feign.IAccountCommandHandler;
import wenjie.chen.transfer.command.TransferCommand;
import wenjie.chen.transfer.commandHandler.ITransferCommandHandler;

@RestController
@Transactional
@RequiredArgsConstructor
@Compensable(
    interfaceClass = ITransferCommandHandler.class,
    confirmableKey = "transferCommandHandlerConfirm",
    cancellableKey = "transferCommandHandlerCancel")
public class TransferController implements ITransferCommandHandler {
    @Qualifier("transferCommandHandler")
    @NonNull
    private final ITransferCommandHandler transferCommandHandler;
    @NonNull
    private final IAccountCommandHandler accountCommandHandler;

    @ResponseBody
    @PostMapping("/transfer")
    @Override
    public void transfer(@RequestBody TransferCommand command) {
        // try - 扣款
        transferCommandHandler.transfer(command);
        // try - 收款
        accountCommandHandler.increaseAmount(IAccountCommandHandler.IncreaseAmountCommand.of(command));

        // throw new IllegalStateException("trigger receiver's cancel phase");
    }
}
